package com.tanhua.server.service;
import org.bson.types.ObjectId;

import com.alibaba.fastjson.JSON;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.SoulVo;
import com.tanhua.dubbo.api.SoulApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SoulService {

    @Reference
    private SoulApi soulApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private final String isLock_LEVEL = "isLock_level_";

    @Reference
    private UserInfoApi userInfoApi;

    //测灵魂-问卷列表
    public ResponseEntity<Object> testSoul() {

        List<Soul> soulList = soulApi.findAllSoul();

        List<SoulVo> voList = setSoulVoList(soulList);
        return ResponseEntity.ok(voList);
    }

    private List<SoulVo> setSoulVoList(List<Soul> soulList) {
        List<SoulVo> soulVoList = new ArrayList<>();
        for (Soul soul : soulList) {
            SoulVo soulVo = new SoulVo();

            BeanUtils.copyProperties(soul, soulVo);
            //soulVo.setId(soul.getQuestion_Id());
            List<SoulTest> optionList = soul.getOptionList();
            List<Question> questions = new ArrayList<>();

            //封装问题
            for (SoulTest soulTest : optionList) {
                String questionText = soulTest.getQuestion();
                Question question = new Question();
                question.setQuestion(questionText);
                question.setId(soul.getQuestion_Id());
                List<Option> options = new ArrayList<>();

                if (soulTest.getOption_A() != null) {
                    String option = soulTest.getOption_A();
                    Option option1 = new Option();
                    option1.setId("A");
                    option1.setOption(option);
                    options.add(option1);
                }
                if (soulTest.getOption_B() != null) {
                    String option1 = soulTest.getOption_B();
                    Option option = new Option();
                    option.setId("B");
                    option.setOption(option1);
                    options.add(option);
                }
                if (soulTest.getOption_C() != null) {
                    String option1 = soulTest.getOption_C();
                    Option option = new Option();
                    option.setId("C");
                    option.setOption(option1);
                    options.add(option);
                }
                if (soulTest.getOption_D() != null) {
                    String option1 = soulTest.getOption_D();
                    Option option = new Option();
                    option.setId("D");
                    option.setOption(option1);
                    options.add(option);
                }
                if (soulTest.getOption_E() != null) {
                    String option1 = soulTest.getOption_E();
                    Option option = new Option();
                    option.setId("E");
                    option.setOption(option1);
                    options.add(option);
                }
                if (soulTest.getOption_F() != null) {
                    String option1 = soulTest.getOption_F();
                    Option option = new Option();
                    option.setId("F");
                    option.setOption(option1);
                    options.add(option);
                }
                if (soulTest.getOption_G() != null) {
                    String option1 = soulTest.getOption_G();
                    Option option = new Option();
                    option.setId("G");
                    option.setOption(option1);
                    options.add(option);
                }

                question.setOptions(options);
                questions.add(question);
            }

            //封装权限锁
            soulVo.setQuestions(questions);

            String isLock = isLock_LEVEL + UserHolder.getUserId();
            String levelStr = redisTemplate.opsForValue().get(isLock);
            if (levelStr == null) {
                redisTemplate.opsForValue().set(isLock, "1");
                levelStr = "1";
            }
            switch (Integer.parseInt(levelStr)) {
                case 1:
                    if (soulVo.getLevel().equals("初级")) {
                        soulVo.setIsLock(0);
                    }
                    break;
                case 2:
                    if (!soulVo.getLevel().equals("高级")) {
                        soulVo.setIsLock(0);
                    }
                    break;
                case 3:
                    soulVo.setIsLock(0);
                    break;
            }

            soulVoList.add(soulVo);
        }

        return soulVoList;
    }

    //测灵魂-提交问卷
    public ResponseEntity<Object> submitSoul(Map<String, List<Answer>> param) {
        List<Answer> answerList = param.get("answers");
        soulApi.remove(answerList.get(0).getQuestionId(), UserHolder.getUserId());
        Double scores = 0d;
        for (int i = 0; i < 10; i++) {

            Answer answer = answerList.get(i);
            double score = 0d;
            String optionId = answer.getOptionId();
            switch (optionId) {
                case "A":
                    score = 2d;
                    break;
                case "B":
                    score = 2d;
                    break;
                case "C":
                    score = 4d;
                    break;
                case "D":
                    score = 4d;
                    break;
                case "E":
                    score = 6d;
                    break;
                case "F":
                    score = 6d;
                    break;
                case "G":
                    score = 10d;
                    break;
            }
            scores += score;
            answer.setScore(score);

            soulApi.save(answer, UserHolder.getUserId());

        }

        UserConclusion userConclusion = new UserConclusion();
        userConclusion.setUserId(UserHolder.getUserId());

        if (scores < 21) {
            userConclusion.setConclusion("猫头鹰");
        } else if (scores >= 21 && scores <= 40) {
            userConclusion.setConclusion("白兔型");
        } else if (scores > 40 && scores <= 55) {
            userConclusion.setConclusion("狐狸型");
        } else {
            userConclusion.setConclusion("狮子型");
        }
        //添加人物性格
        soulApi.saveUserConclusion(userConclusion);
        Soul soul = soulApi.find(answerList.get(0).getQuestionId());
        String key = isLock_LEVEL + UserHolder.getUserId();
        if (soul != null) {
            Integer star = soul.getStar();
            switch (star) {
                case 2:
                    redisTemplate.opsForValue().set(key, "2");
                    break;
                case 3:
                    redisTemplate.opsForValue().set(key, "3");
                    break;
            }
        }
        return ResponseEntity.ok(soul.getQuestion_Id());
    }

    //接口名称：测灵魂-查看结果
    public ResponseEntity<Object> reportSoul(String id) {

        List<Answer> answerList = soulApi.findByIdToAnswer(UserHolder.getUserId(), id);
        double score = 0d;
        for (Answer answer : answerList) {
            score += answer.getScore();
        }

        Map<String, Object> result = new HashMap<>();

        setreportSoulResult(result, score);

        return ResponseEntity.ok(result);
    }

    //封装结果数据
    private void setreportSoulResult(Map<String, Object> result, Double score) {

        String conclusions = soulApi.findUserConclusions(UserHolder.getUserId());

        if (conclusions.equals("猫头鹰")) {
            String conclusion = "猫头鹰：他们的共同特质为重计划、条理、细节精准。在行为上，表现出喜欢理性思考与分析、较重视制度、结构、规范。他们注重执行游戏规则、循规蹈矩、巨细靡遗、重视品质、敬业负责。";
            result.put("conclusion", conclusion);
            result.put("cover", "https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/owl.png");

        } else if (conclusions.equals("白兔型")) {
            String conclusion = "白兔型：平易近人、敦厚可靠、避免冲突与不具批判性。在行为上，表现出不慌不忙、冷静自持的态度。他们注重稳定与中长程规划，现实生活中，常会反思自省并以和谐为中心，即使面对困境，亦能泰然自若，从容应付。";
            result.put("conclusion", conclusion);
            result.put("cover", "https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/rabbit.png");

        } else if (conclusions.equals("狐狸型")) {
            String conclusion = "狐狸型 ：人际关系能力极强，擅长以口语表达感受而引起共鸣，很会激励并带动气氛。他们喜欢跟别人互动，重视群体的归属感，基本上是比较「人际导向」。由于他们富同理心并乐于分享，具有很好的亲和力，在服务业、销售业、传播业及公共关系等领域中，狐狸型的领导者都有很杰出的表现。";
            result.put("conclusion", conclusion);
            result.put("cover", "https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/fox.png");

        } else {
            String conclusion = "狮子型：性格为充满自信、竞争心强、主动且企图心强烈，是个有决断力的领导者。一般而言，狮子型的人胸怀大志，勇于冒险，看问题能够直指核心，并对目标全力以赴。他们在领导风格及决策上，强调权威与果断，擅长危机处理，此种性格最适合开创性与改革性的工作。";
            result.put("conclusion", conclusion);
            result.put("cover", "https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/lion.png");

        }

        List<Map<String, String>> dimensions = new ArrayList<>();

        Map<String, String> map1 = new HashMap<>();
        map1.put("key", "外向");
        map1.put("value", "80%");
        dimensions.add(map1);

        Map<String, String> map2 = new HashMap<>();
        map2.put("key", "判断");
        map2.put("value", "70%");
        dimensions.add(map2);

        Map<String, String> map3 = new HashMap<>();
        map3.put("key", "抽象");
        map3.put("value", "90%");
        dimensions.add(map3);

        Map<String, String> map4 = new HashMap<>();
        map4.put("key", "理性");
        map4.put("value", "60%");
        dimensions.add(map4);

        result.put("dimensions", dimensions);

        List<Long> userIdList = soulApi.queryUserIdByConclusion(conclusions);

        List<UserInfo> userInfoList = userInfoApi.findByIdList(userIdList, UserHolder.getUserId());

        List<Map<String, Object>> similarYou = new ArrayList<>();
        if (userInfoList != null || userInfoList.size() != 0) {
            for (UserInfo userInfo : userInfoList) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", userInfo.getId());
                map.put("avatar", userInfo.getAvatar());
                similarYou.add(map);
            }
        }
        result.put("similarYou", similarYou);
    }
}